package com.cui.project.controller;

import com.api.apiclientsdk.client.ApiClient;
import com.api.apiclientsdk.model.InterfaceInfoInvokeParams;
import com.api.common.alert.CommonAlertHelper;
import com.api.common.common.*;
import com.api.common.model.dto.ServerDto;
import com.api.common.model.entity.InterfaceInfo;
import com.api.common.model.entity.User;
import com.api.common.model.entity.UserInterfaceFavorite;
import com.api.common.model.entity.UserInterfaceInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cui.project.manager.APIDynamicRouteManager;
import com.cui.project.mapper.UserInterfaceFavoriteMapper;
import com.cui.project.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.cui.project.model.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.cui.project.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.cui.project.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.cui.project.service.UserInterfaceInfoService;
import com.google.gson.Gson;
import com.cui.project.annotation.AuthCheck;
import com.api.common.constant.CommonConstant;
import com.cui.project.constant.PageConstants;
import com.cui.project.constant.RedisConstant;
import com.cui.project.exception.BusinessException;
import com.cui.project.manager.RedisLimiterManager;
import com.cui.project.model.enums.InterfaceInfoStatusEnum;
import com.cui.project.model.vo.InterfaceInfoRandVO;
import com.cui.project.model.vo.InterfaceInfoVO;
import com.cui.project.service.InterfaceInfoService;
import com.cui.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RateIntervalUnit;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * 帖子接口
 *
 * @author cui
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;
    @Resource
    private UserService userService;
    @Resource
    private ApiClient apiClient;
    @Resource
    private APIDynamicRouteManager apiDynamicRouteManager;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource(name = "alertExecutor")
    private Executor executor;

    @Resource
    private CommonAlertHelper alertHelper;

    @Resource
    private UserInterfaceFavoriteMapper userInterfaceFavoriteMapper;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        if (!interfaceInfoService.save(interfaceInfo)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        Gson gson = new Gson();
        apiDynamicRouteManager.sendMessage(gson.toJson(interfaceInfo));
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        /**
         * 更新后也要发送rabbitmq通知api网关更新route
         */
        boolean result = interfaceInfoService.updateById(interfaceInfo);

        if(result){
            CompletableFuture.runAsync(()->{
                try {
                    Gson gson = new Gson();
                    InterfaceInfo info = interfaceInfoService.getById(id);
                    apiDynamicRouteManager.sendMessage(gson.toJson(info));
                    log.info("接口更新成功，已通知网关刷新路由：interfaceId={}", info.getId());
                } catch (Exception e) {
                    log.error("通知网关刷新路由失败：interfaceId={}", id, e);
                    // 可以加入重试队列
                }
            },executor).exceptionally(ex->{
                log.error("异步任务执行失败", ex);
                return null;
            });
        }

        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        queryWrapper.eq("interfaceInfoId", interfaceInfo.getId());
        queryWrapper.select("userId", "interfaceInfoId", "totalNum", "leftNum");
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getOne(queryWrapper);

        //用户首次查看接口时，可能没有记录
        if(userInterfaceInfo!=null){
            interfaceInfoVO.setTotalNum(userInterfaceInfo.getLeftNum());
        }else{
             interfaceInfoVO.setTotalNum(0); // 首次查看，显示0次
        }

        //获取api网关地址
        Object serverList = redisTemplate.opsForValue().get(com.api.common.constant.RedisConstant.SERVER_IP_LIST_KEY);
        if(serverList==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "网关服务器列表为空，请联系管理员");
        }

        List<ServerDto> serverDtoList = (List<ServerDto>) serverList;
        if(CollectionUtils.isEmpty(serverDtoList)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "网关服务器列表为空，请联系管理员");
        }
        ServerDto serverDto = serverDtoList.get(0);

        interfaceInfoVO.setHost(serverDto.getUrl());

        //获取收藏信息
        LambdaQueryWrapper<UserInterfaceFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInterfaceFavorite::getUserId,loginUser.getId());
        wrapper.eq(UserInterfaceFavorite::getInterfaceInfoId,interfaceInfo.getId());
        wrapper.select(UserInterfaceFavorite::getStatus);
        UserInterfaceFavorite favorite = userInterfaceFavoriteMapper.selectOne(wrapper);
        interfaceInfoVO.setLiked(favorite.getStatus());

        return ResultUtils.success(interfaceInfoVO);
    }


    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // content 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > PageConstants.MAX_PAGE_SIZE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }


    /**
     * 分页获取列表 (ES查询)
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/search/list/page")
    public BaseResponse<Page<InterfaceInfo>> searchListInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userService.getLoginUser(request);
        long size = interfaceInfoQueryRequest.getPageSize();
        // 限制爬虫
        if (size > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<InterfaceInfo> infoPage = interfaceInfoService.searchFromEs(interfaceInfoQueryRequest);
        return ResultUtils.success(infoPage);
    }
    // endregion


    /**
     * 接口发布 / 下线的功能
     * 权限控制：仅管理员可操作。
     */

    /**
     * 发布
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
//    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long idRequestId = idRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(idRequestId);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断接口是否可用（调用编写号的sdk来验证）
        User user = userService.getLoginUser(request);
        String accessKey = user.getAccessKey();
        String secretKey = user.getSecretKey();
        String url = oldInterfaceInfo.getUrl();
        String method = oldInterfaceInfo.getMethod();
        String host = oldInterfaceInfo.getHost();
        String requestParams = oldInterfaceInfo.getRequestParams();
        String usernameByPost = apiClient.request(host + url, method, requestParams.trim(), accessKey, secretKey);
        if (StringUtils.isBlank(usernameByPost)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败");
        }

        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(idRequestId);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);

        return ResultUtils.success(result);
    }

    /**
     * 下线
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
//    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                      HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long idRequestId = idRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(idRequestId);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User user = userService.getLoginUser(request);

        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(idRequestId);
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);

        return ResultUtils.success(result);
    }

    /**
     * 测试调用
     * todo 要加限流
     *
     * @param interfaceInfoInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<String> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        if (interfaceInfoInvokeRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User user = userService.getLoginUser(request);

        Long id = interfaceInfoInvokeRequest.getId();
        InterfaceInfo oldInterfaceInfo = null;
        if(id!=null&&id<=0)
            oldInterfaceInfo=interfaceInfoService.getById(id);

        // 限流每分钟最多10次，一次一个令牌
        String limiterKey=String.format(RedisConstant.INTERFACEINFO_INVOKEINTERFACEINFO,user.getId());
        try {
            //付费免费测试3个小时只能测试100次，免费每秒10次
            if(oldInterfaceInfo!=null&&oldInterfaceInfo.getFree().equals(InterfaceInfoStatusEnum.PAY.getValue())){
                redisLimiterManager.doRateLimit(limiterKey,100,3, RateIntervalUnit.HOURS,1);
            }else{
                redisLimiterManager.doRateLimit(limiterKey,10,1, RateIntervalUnit.SECONDS,1);
            }

        }catch (BusinessException e){
            //触发限流时发送告警
            if(e.getCode()==ErrorCode.TOO_MANY_REQUEST.getCode()){
                alertHelper.apiRateLimit(
                        "测试调用接口",
                        user.getUserAccount(),
                        10,
                        user.getEmail() // 发送到用户邮箱
                );
            }
        }
        // 获取api网关地址
        ServerDto gateway = getAvailableGateway();

        InterfaceInfoInvokeParams params=buildInvokeParams(interfaceInfoInvokeRequest,user,oldInterfaceInfo);

        // 调用接口
        String result = apiClient.request(
                gateway.getUrl() + params.getUrl(),
                params.getMethod(),
                params.getParams(),
                user.getAccessKey(),
                user.getSecretKey()
        );
        try {
            Gson gson = new Gson();
            BaseResponse baseResponse = gson.fromJson(result, BaseResponse.class);
            return baseResponse;
        } catch (Exception e) {
            return ResultUtils.success(result);
        }

    }

    private InterfaceInfoInvokeParams buildInvokeParams(InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, User user,InterfaceInfo oldInterfaceInfo) {
        Long id = interfaceInfoInvokeRequest.getId();
        String userRequestParams = Optional.ofNullable(interfaceInfoInvokeRequest.getUserRequestParams()).orElse("");

        InterfaceInfoInvokeParams.InterfaceInfoInvokeParamsBuilder builder = InterfaceInfoInvokeParams.builder();
        builder.accessKey(user.getAccessKey())
                .secretKey(user.getSecretKey());

        //todo 调用接口和测试接口要进行分开，因为有的接口是免费的和付费的，付费的接口会提供测试接口
        if (!(id == null || id <= 0)) {
            // 判断是否存在
            if (oldInterfaceInfo == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            if (oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已关闭");
            }

            String url = oldInterfaceInfo.getUrl();
            String host = oldInterfaceInfo.getHost();
            String method = oldInterfaceInfo.getMethod();
            String requestHeader = oldInterfaceInfo.getRequestHeader();
            String responseHeader = oldInterfaceInfo.getResponseHeader();
            Gson gson = new Gson();
            Map<String, Object> map = gson.fromJson(userRequestParams, Map.class);

            map.put("id", String.valueOf(oldInterfaceInfo.getId()));
            String params = gson.toJson(map);

            builder
                    .url(url)
                    .method(method)
                    .params(params);

        } else {
            //添加新的接口时，点击测试接口是否可以用，这边因为是测试，接口还未添加
            String url = interfaceInfoInvokeRequest.getUrl();
            String requestHeader = interfaceInfoInvokeRequest.getRequestHeader();
            String requestParams = interfaceInfoInvokeRequest.getRequestParams();
            String responseHeader = interfaceInfoInvokeRequest.getResponseHeader();
            String host = interfaceInfoInvokeRequest.getHost();
            String method = interfaceInfoInvokeRequest.getMethod();
            builder
                    .url(url)
                    .method(method)
                    .params(requestParams);
        }
        return builder.build();
    }

    private ServerDto getAvailableGateway() {
        List<ServerDto> serverDtoList = (List<ServerDto>) redisTemplate.opsForValue().get(com.api.common.constant.RedisConstant.SERVER_IP_LIST_KEY);
        if(CollectionUtils.isEmpty(serverDtoList)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "网关服务器不可用");
        }
        ServerDto serverDto = serverDtoList.get(0);
        return serverDto;
    }

    @GetMapping("/get/rand")
    public BaseResponse<List<InterfaceInfoRandVO>> getInterfaceInfoRand(Integer size, HttpServletRequest request) {
        if (size <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userService.getLoginUser(request);
        return ResultUtils.success(interfaceInfoService.rand(size));
    }


    /**
     * 获取当前用户上传接口的接口id和name
     * @param request
     * @return
     */
    @GetMapping("/interface/names")
    public BaseResponse<List<InterfaceInfoVO>> getInterfaceNames(
            @RequestParam Integer type, HttpServletRequest request){
        TrafficForecastController.AnalysisTypeEnum analysisEnum = TrafficForecastController.AnalysisTypeEnum.get(type);
        if(analysisEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未知 type="+type);
        }
        User user = userService.getLoginUser(request);

        List<InterfaceInfo> interfaceInfos = null;

        if(TrafficForecastController.AnalysisTypeEnum.use.getType().equals(type)){
            interfaceInfos = interfaceInfoService.getNames(user.getId());
        }else{
            LambdaQueryWrapper<InterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
            boolean all = TrafficForecastController.AnalysisTypeEnum.all.getType().equals(type);
            if(all&&!userService.isAdmin(request)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            //当前用户上传的接口 否则就是管理员查询所有数据
            queryWrapper.eq(!all,InterfaceInfo::getUserId,user.getId());

            queryWrapper.select(InterfaceInfo::getId,InterfaceInfo::getName);
            interfaceInfos = interfaceInfoService.list(queryWrapper);
        }

        if(interfaceInfos.isEmpty()){
            log.debug("当前用户上传接口为空");
            return ResultUtils.success(Collections.emptyList());
        }
        List<InterfaceInfoVO> result = interfaceInfos.stream().map(InterfaceInfoVO::getToVo).collect(Collectors.toList());
        return ResultUtils.success(result);
    }
}
